package com.sahooz.library;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.style.cityjd.JDCityConfig;
import com.lljjcoder.style.cityjd.JDCityPicker;

import java.util.ArrayList;
import java.util.List;

public class CountryPickFragment extends Fragment {

    private ArrayList<Country> selectedCountries = new ArrayList<>();
    private ArrayList<Country> allCountries = new ArrayList<>();
    private boolean isShowChinaProvice = false;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_country_pick, null);
        if(getArguments()!=null){
            isShowChinaProvice = getArguments().getBoolean("isShowChinaProvice",false);
        }
        RecyclerView rvPick = (RecyclerView) inflate.findViewById(R.id.rv_pick);
        SideBar side = (SideBar) inflate.findViewById(R.id.side);
        EditText etSearch = (EditText) inflate.findViewById(R.id.et_search);
        TextView tvLetter = (TextView) inflate.findViewById(R.id.tv_letter);
        ImageView ivBack = (ImageView) inflate.findViewById(R.id.iv_back);
        allCountries.clear();
        allCountries.addAll(Country.getAll(getActivity(), null));
        selectedCountries.clear();
        selectedCountries.addAll(allCountries);
        final CAdapter adapter = new CAdapter(selectedCountries);
        rvPick.setAdapter(adapter);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        rvPick.setLayoutManager(manager);
        rvPick.setAdapter(adapter);
//        rvPick.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String string = s.toString();
                selectedCountries.clear();
                for (Country country : allCountries) {
                    if (country.name.toLowerCase().contains(string.toLowerCase())
                            || country.codeStr.replaceAll(" ", "").contains(string)
                            || country.getPinyin().toLowerCase().contains(string.toLowerCase())
                    )
                        selectedCountries.add(country);
                }
                adapter.update(selectedCountries);
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
//        side.addIndex("#", side.indexes.size());
        side.setOnLetterChangeListener(new SideBar.OnLetterChangeListener() {
            @Override
            public void onLetterChange(String letter) {
                tvLetter.setVisibility(View.VISIBLE);
                tvLetter.setText(letter);
                int position = adapter.getLetterPosition(letter);
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position, 0);
                }
            }

            @Override
            public void onReset() {
                tvLetter.setVisibility(View.GONE);
            }
        });
        return inflate;
    }


    class CAdapter extends PyAdapter<RecyclerView.ViewHolder> {

        public CAdapter(List<? extends PyEntity> entities) {
            super(entities);
        }

        @Override
        public RecyclerView.ViewHolder onCreateLetterHolder(ViewGroup parent, int viewType) {
            return new LetterHolder(getLayoutInflater().inflate(R.layout.item_letter, parent, false));
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            return new VH(getLayoutInflater().inflate(R.layout.item_country, parent, false));
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, PyEntity entity, int position) {
            VH vh = (VH) holder;
            final Country country = (Country) entity;
            vh.ivFlag.setImageResource(country.flag);
            vh.tvName.setText(country.name);
            vh.tvCode.setText("+" + country.code);
            holder.itemView.setOnClickListener(v -> {
                if(isShowChinaProvice&&country.code == 86){
                    JDCityPicker cityPicker = new JDCityPicker();
                    JDCityConfig jdCityConfig = new JDCityConfig.Builder().build();
                    jdCityConfig.setShowType(JDCityConfig.ShowType.PRO_CITY);
                    cityPicker.init(getContext());
                    cityPicker.setConfig(jdCityConfig);
                    cityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
                        @Override
                        public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                            Intent data = new Intent();
                            data.putExtra("country", country.toJson());
                            data.putExtra("province", province);
                            data.putExtra("city", city);
                            getActivity().setResult(Activity.RESULT_OK, data);
                            getActivity().finish();
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
                    cityPicker.showCityPicker();
                    return;
                }
                Intent data = new Intent();
                data.putExtra("country", country.toJson());
                getActivity().setResult(Activity.RESULT_OK, data);
                getActivity().finish();
            });
        }

        @Override
        public void onBindLetterHolder(RecyclerView.ViewHolder holder, LetterEntity entity, int position) {
            ((LetterHolder) holder).textView.setText(entity.letter.toUpperCase());
            if (position == 0) {
                ((LetterHolder) holder).line.setVisibility(View.GONE);
            } else {
                ((LetterHolder) holder).line.setVisibility(View.VISIBLE);
            }
        }
    }
}
